// var a;
// var s;
// var $macros = require("./AL_Framework_Macros");
// (s = a || (a = {}))[(s.Done = 1)] = "Done";
// s[(s.Failed = 2)] = "Failed";
// s[(s.Waiting = 3)] = "Waiting";
// var c = (function () {
//     function e() {
//         this.logTag = "[AL_Framework_Popup_Manager]";
//         this._jiedian_huancun = new Map();
//         this._current = null;
//         this._queue = [];
//         this._suspended = [];
//         this.locked = !1;
//         this.interval = 0.05;
//         this.loadStartCallback = function () {};
//         this.loadFinishCallback = function () {};
//     }
//     e.Instance = function () {
//         return this._instance || (this._instance = new e());
//     };
//     Object.defineProperty(e.prototype, "jiedian_huancun", {
//         get: function () {
//             return this._jiedian_huancun;
//         },
//         enumerable: !1,
//         configurable: !0
//     });
//     Object.defineProperty(e.prototype, "current", {
//         get: function () {
//             return this._current;
//         },
//         enumerable: !1,
//         configurable: !0
//     });
//     Object.defineProperty(e.prototype, "queue", {
//         get: function () {
//             return this._queue;
//         },
//         enumerable: !1,
//         configurable: !0
//     });
//     Object.defineProperty(e.prototype, "suspended", {
//         get: function () {
//             return this._suspended;
//         },
//         enumerable: !1,
//         configurable: !0
//     });
//     e.prototype.show = function (e) {
//         var t = this;
//         return new Promise(function (o) {
//             return __awaiter(t, void 0, void 0, function () {
//                 var t;
//                 var s;
//                 var r;
//                 var c = this;
//                 return __generator(this, function (l) {
//                     switch (l.label) {
//                         case 0:
//                             return e
//                                 ? ((e = this.jiexi_canshu(e)),
//                                   this._current || this.locked
//                                       ? e && e.immediately
//                                           ? ((this.locked = !1), [4, this.suspend(e.hideCurrent)])
//                                           : [3, 2]
//                                       : [3, 3])
//                                 : [
//                                       2,
//                                       o({
//                                           state: a.Failed
//                                       })
//                                   ];
//                         case 1:
//                             l.sent();
//                             return [3, 3];
//                         case 2:
//                             this.push(e);
//                             o({
//                                 state: a.Waiting
//                             });
//                             return [2];
//                         case 3:
//                             this._current = {
//                                 params: e
//                             };
//                             t = this.huoqu_jiedian_cong_huancun_zhong(e);
//                             if (this.loadStartCallback) {
//                                 this.loadStartCallback();
//                             }
//                             return [4, Manager.uiManager.open(e)];
//                         case 4:
//                             return (s = l.sent())
//                                 ? ((t = s.node), this.loadFinishCallback && this.loadFinishCallback(), [3, 6])
//                                 : (Log.w(this.logTag, "未找到弹窗预制体", cc.js.getClassName(e.type)),
//                                   this.loadFinishCallback && this.loadFinishCallback(),
//                                   o({
//                                       state: a.Failed
//                                   }),
//                                   [2]);
//                         case 5:
//                             if (!t.parent) {
//                                 Manager.uiManager.tianjia_shitu(t);
//                             }
//                             if (this.loadFinishCallback) {
//                                 this.loadFinishCallback();
//                             }
//                             l.label = 6;
//                         case 6:
//                             return cc.isValid(t)
//                                 ? (r = t.getComponent(e.type))
//                                     ? ((r.params = e),
//                                       (this._current.popup = r),
//                                       (this._current.node = r.node),
//                                       (r.request = this._current),
//                                       (t.zIndex = 10 + (e.zIndex || 0)),
//                                       (r.finishCallback = function (o) {
//                                           return __awaiter(c, void 0, void 0, function () {
//                                               var i = this;
//                                               return __generator(this, function (n) {
//                                                   switch (n.label) {
//                                                       case 0:
//                                                           return o
//                                                               ? [2]
//                                                               : ((this.locked =
//                                                                     this._suspended.length > 0 ||
//                                                                     this._queue.length > 0),
//                                                                 this.recycle(e, t, e.mode),
//                                                                 this._current != r.request
//                                                                     ? [3, 2]
//                                                                     : ((this._current = null),
//                                                                       [
//                                                                           4,
//                                                                           new Promise(function (e) {
//                                                                               cc.Canvas.instance.scheduleOnce(
//                                                                                   e,
//                                                                                   i.interval
//                                                                               );
//                                                                           })
//                                                                       ]));
//                                                       case 1:
//                                                           n.sent();
//                                                           this.next();
//                                                           n.label = 2;
//                                                       case 2:
//                                                           return [2];
//                                                   }
//                                               });
//                                           });
//                                       }),
//                                       (r.xiaohui_huidiao = function () {
//                                           var e = c._suspended.indexOf(r.request);
//                                           if (e >= 0) {
//                                               c._suspended.removeAt(e);
//                                           }
//                                           if ((e = c._queue.indexOf(r.request)) >= 0) {
//                                               c._queue.removeAt(e);
//                                           }
//                                           if (c._current == r.request) {
//                                               c._current = null;
//                                           }
//                                       }),
//                                       o({
//                                           state: a.Done,
//                                           target: r
//                                       }),
//                                       [2])
//                                     : (Log.w(this.logTag, "未找到弹窗组件", cc.js.getClassName(e.type)),
//                                       (this._current = null),
//                                       o({
//                                           state: a.Failed
//                                       }),
//                                       [2])
//                                 : (Log.w(this.logTag, "弹窗已被销毁", cc.js.getClassName(e.type)),
//                                   (this._current = null),
//                                   o({
//                                       state: a.Failed
//                                   }),
//                                   [2]);
//                     }
//                 });
//             });
//         });
//     };
//     e.prototype.hide = function (e) {
//         if (cc.isValid(this._current.popup)) {
//             this._current.popup.hide(!1, e);
//         }
//     };
//     e.prototype.yincang_suoyou = function () {
//         if (this._current) {
//             this._current.popup.hide();
//             this.recycle(this._current.params, this._current.node, this.current.params.mode);
//         }
//         var e = 0;
//         for (var t = this._suspended; e < t.length; e++) {
//             if ((n = t[e]) && n.popup) {
//                 n.popup.hide();
//                 this.recycle(n.params, n.node, n.params.mode);
//             }
//         }
//         var o = 0;
//         for (var i = this._queue; o < i.length; o++) {
//             var n;
//             if ((n = i[o]) && n.popup) {
//                 n.popup.hide();
//                 this.recycle(n.params, n.node, n.params.mode);
//             }
//         }
//         this._queue = [];
//         this._suspended = [];
//         this._current = null;
//         this.locked = !1;
//     };
//     e.prototype.next = function () {
//         if (!(this._current || (0 === this._suspended.length && 0 === this._queue.length))) {
//             var e = null;
//             e = this._suspended.length > 0 ? this._suspended.shift() : this._queue.shift();
//             this.locked = !1;
//             if (cc.isValid(e.popup)) {
//                 this._current = e;
//                 if (!e.node.parent) {
//                     Manager.uiManager.tianjia_shitu(e.node);
//                 }
//                 return void (e.popup.isHide && e.popup.show(e.params.args));
//             }
//             this.show(e.params);
//         }
//     };
//     e.prototype.recycle = function (e, t, o) {
//         var i = cc.js.getClassName(e.type);
//         switch (o) {
//             case $macros.Define.CacheMode.Once:
//             case $macros.Define.CacheMode.Normal:
//                 this._jiedian_huancun.delete(i);
//                 Manager.uiManager.close(e.type);
//                 break;
//             case $macros.Define.CacheMode.Frequent:
//                 t.removeFromParent(!1);
//                 this._jiedian_huancun.set(i, t);
//         }
//     };
//     e.prototype.huoqu_jiedian_cong_huancun_zhong = function (e) {
//         var t = cc.js.getClassName(e.type);
//         var o = this._jiedian_huancun;
//         if (o.has(t)) {
//             var i = o.get(t);
//             if (cc.isValid(i)) {
//                 return i;
//             }
//             o.delete(t);
//         }
//         return null;
//     };
//     e.prototype.push = function (e) {
//         this._current || this.locked
//             ? (this._queue.push({
//                   params: e
//               }),
//               this._queue.sort(function (e, t) {
//                   return e.params.zIndex - t.params.zIndex;
//               }))
//             : this.show(e);
//     };
//     e.prototype.suspend = function (e) {
//         return __awaiter(this, void 0, void 0, function () {
//             var t;
//             return __generator(this, function (o) {
//                 switch (o.label) {
//                     case 0:
//                         return this._current
//                             ? this._current.popup
//                                 ? ((t = this._current), this._suspended.push(t), [4, t.popup.chuli_suspended()])
//                                 : ((this._current = null), [2])
//                             : [2];
//                     case 1:
//                         o.sent();
//                         return e ? [4, t.popup.hide(!0)] : [3, 3];
//                     case 2:
//                         o.sent();
//                         o.label = 3;
//                     case 3:
//                         this._current = null;
//                         return [2];
//                 }
//             });
//         });
//     };
//     e.prototype.jiexi_canshu = function (e) {
//         if (null == e.mode) {
//             e.mode = $macros.Define.CacheMode.Normal;
//         }
//         if (void 0 === e.shifou_yanchi_shifang_ziyuan) {
//             e.mode == $macros.Define.CacheMode.Once ? (e.shifou_yanchi_shifang_ziyuan = !1) : (e.shifou_yanchi_shifang_ziyuan = !0);
//         }
//         if (null == e.zIndex) {
//             e.zIndex = 0;
//         }
//         if (null == e.immediately) {
//             e.immediately = !1;
//         }
//         return e;
//     };
//     e._instance = null;
//     return e;
// })();
// exports.default = c;


let statusEnum;
let status;
const $macros = require("./AL_Framework_Macros");

// 定义状态枚举
(status = statusEnum || (statusEnum = {}))[(status.Done = 1)] = "Done";
status[(status.Failed = 2)] = "Failed";
status[(status.Waiting = 3)] = "Waiting";

// 弹窗管理类
class AL_Framework_Popup_Manager {
    constructor() {
        this.logTag = "[AL_Framework_Popup_Manager]";
        this._jiedian_huancun = new Map();
        this._current = null;
        this._queue = [];
        this._suspended = [];
        this.locked = false;
        this.interval = 0.05;
        this.loadStartCallback = () => {};
        this.loadFinishCallback = () => {};
    }

    /** 获取单例 */
    static Instance() {
        if (!this._instance) {
            this._instance = new AL_Framework_Popup_Manager();
        }
        return this._instance;
    }

    /** 获取缓存节点 */
    get jiedian_huancun() {
        return this._jiedian_huancun;
    }

    /** 获取当前弹窗 */
    get current() {
        return this._current;
    }

    /** 获取弹窗队列 */
    get queue() {
        return this._queue;
    }

    /** 获取暂停的弹窗 */
    get suspended() {
        return this._suspended;
    }

    /** 显示弹窗 */
    async show(params) {
        if (!params) {
            return { state: statusEnum.Failed };
        }

        params = this.jiexi_canshu(params);

        if (this._current || this.locked) {
            if (params.immediately) {
                this.locked = false;
                await this.suspend(params.hideCurrent);
            } else {
                this.push(params);
                return { state: statusEnum.Waiting };
            }
        } else {
            this._current = { params };
            let node = this.huoqu_jiedian_cong_huancun_zhong(params);

            if (this.loadStartCallback) {
                this.loadStartCallback();
            }

            const managerResponse = await Manager.uiManager.open(params);
            if (managerResponse) {
                node = managerResponse.node;
                this.loadFinishCallback && this.loadFinishCallback();
            } else {
                Log.w(this.logTag, "未找到弹窗预制体", cc.js.getClassName(params.type));
                this.loadFinishCallback && this.loadFinishCallback();
                return { state: statusEnum.Failed };
            }

            if (!node.parent) {
                Manager.uiManager.tianjia_shitu(node);
            }
            this.loadFinishCallback && this.loadFinishCallback();

            if (cc.isValid(node)) {
                let popupComponent = node.getComponent(params.type);
                if (popupComponent) {
                    popupComponent.params = params;
                    this._current.popup = popupComponent;
                    this._current.node = popupComponent.node;
                    popupComponent.request = this._current;
                    node.zIndex = 10 + (params.zIndex || 0);

                    popupComponent.finishCallback = async (isFinished) => {
                        if (!isFinished) {
                            this.locked = this._suspended.length > 0 || this._queue.length > 0;
                            this.recycle(params, node, params.mode);

                            if (this._current == popupComponent.request) {
                                this._current = null;
                                await new Promise((resolve) => {
                                    cc.Canvas.instance.scheduleOnce(resolve, this.interval);
                                });
                                this.next();
                            }
                        }
                    };

                    popupComponent.xiaohui_huidiao = () => {
                        let index = this._suspended.indexOf(popupComponent.request);
                        if (index >= 0) {
                            this._suspended.splice(index, 1);
                        }
                        index = this._queue.indexOf(popupComponent.request);
                        if (index >= 0) {
                            this._queue.splice(index, 1);
                        }
                        if (this._current === popupComponent.request) {
                            this._current = null;
                        }
                    };

                    return { state: statusEnum.Done, target: popupComponent };
                } else {
                    Log.w(this.logTag, "未找到弹窗组件", cc.js.getClassName(params.type));
                    this._current = null;
                    return { state: statusEnum.Failed };
                }
            } else {
                Log.w(this.logTag, "弹窗已被销毁", cc.js.getClassName(params.type));
                this._current = null;
                return { state: statusEnum.Failed };
            }
        }
    }

    /** 隐藏弹窗 */
    hide(isImmediate) {
        if (cc.isValid(this._current.popup)) {
            this._current.popup.hide(false, isImmediate);
        }
    }

    /** 隐藏所有弹窗 */
    yincang_suoyou() {
        if (this._current) {
            this._current.popup.hide();
            this.recycle(this._current.params, this._current.node, this._current.params.mode);
        }

        this._suspended.forEach((suspendedPopup) => {
            if (suspendedPopup && suspendedPopup.popup) {
                suspendedPopup.popup.hide();
                this.recycle(suspendedPopup.params, suspendedPopup.node, suspendedPopup.params.mode);
            }
        });

        this._queue.forEach((queuedPopup) => {
            if (queuedPopup && queuedPopup.popup) {
                queuedPopup.popup.hide();
                this.recycle(queuedPopup.params, queuedPopup.node, queuedPopup.params.mode);
            }
        });

        this._queue = [];
        this._suspended = [];
        this._current = null;
        this.locked = false;
    }

    /** 显示下一个弹窗 */
    next() {
        if (!this._current && (this._suspended.length > 0 || this._queue.length > 0)) {
            let nextPopup = this._suspended.length > 0 ? this._suspended.shift() : this._queue.shift();
            this.locked = false;

            if (cc.isValid(nextPopup.popup)) {
                this._current = nextPopup;
                if (!nextPopup.node.parent) {
                    Manager.uiManager.tianjia_shitu(nextPopup.node);
                }
                if (nextPopup.popup.isHide) {
                    nextPopup.popup.show(nextPopup.params.args);
                }
            } else {
                this.show(nextPopup.params);
            }
        }
    }

    /** 回收弹窗 */
    recycle(params, node, mode) {
        const className = cc.js.getClassName(params.type);
        switch (mode) {
            case $macros.Define.CacheMode.Once:
            case $macros.Define.CacheMode.Normal:
                this._jiedian_huancun.delete(className);
                Manager.uiManager.close(params.type);
                break;
            case $macros.Define.CacheMode.Frequent:
                node.removeFromParent(false);
                this._jiedian_huancun.set(className, node);
                break;
        }
    }

    /** 从缓存中获取节点 */
    huoqu_jiedian_cong_huancun_zhong(params) {
        const className = cc.js.getClassName(params.type);
        if (this._jiedian_huancun.has(className)) {
            const cachedNode = this._jiedian_huancun.get(className);
            if (cc.isValid(cachedNode)) {
                return cachedNode;
            }
            this._jiedian_huancun.delete(className);
        }
        return null;
    }

    /** 添加到队列 */
    push(params) {
        if (this._current || this.locked) {
            this._queue.push({ params });
            this._queue.sort((a, b) => a.params.zIndex - b.params.zIndex);
        } else {
            this.show(params);
        }
    }

    /** 暂停当前弹窗 */
    async suspend(hideCurrent) {
        if (this._current) {
            if (this._current.popup) {
                let currentPopup = this._current;
                this._suspended.push(currentPopup);
                await currentPopup.popup.chuli_suspended();
                if (hideCurrent) {
                    await currentPopup.popup.hide(true);
                }
            } else {
                this._current = null;
            }
        }
    }

    /** 解析参数 */
    jiexi_canshu(params) {
        if (params.mode == null) {
            params.mode = $macros.Define.CacheMode.Normal;
        }
        if (params.shifou_yanchi_shifang_ziyuan === undefined) {
            params.shifou_yanchi_shifang_ziyuan = params.mode === $macros.Define.CacheMode.Once ? false : true;
        }
        if (params.zIndex == null) {
            params.zIndex = 0;
        }
        if (params.immediately == null) {
            params.immediately = false;
        }
        return params;
    }
}

AL_Framework_Popup_Manager._instance = null;
exports.default = AL_Framework_Popup_Manager;
